package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.crm.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.PlatformApi;
import com.jmp.base.dto.UserMergeDto;
import com.jmp.feign.UserFeign;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.ConvertUtils;
import one.stand.dto.MenuTreeDto;
import one.stand.dto.PageResponse2;
import one.stand.mapper.CompanyApiCrmMapper;
import one.stand.mapper.CompanyPlatformMapperExt;
import one.stand.mapper.UserApiMapper;
import one.stand.model.Company;
import one.stand.model.CompanyPlatform;
import one.stand.model.ResultModel;
import one.stand.model.User;
import one.stand.service.CompanyBaseService;
import one.stand.service.user.MenuService;
import one.stand.util.AssertUtil;
import one.stand.util.OneListUtil;
import one.stand.util.RequestContextHolder;
import one.stand.util.SqlUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("crmPc/user")
public class UserController {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private CompanyPlatformMapperExt companyPlatformMapperExt;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private MenuService menuService;

    @Autowired
    private CompanyApiCrmMapper companyApiCrmMapper;
    @Autowired
    private UserApiMapper userApiMapper;

    @ApiOperation(value = "用户信息")
    @PostMapping("info")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<UserInfoResponse> info() {
        final Integer userCompanyId = RequestContextHolder.getRequestContext().getUser().getCompanyId();
        final Integer userId = RequestContextHolder.getRequestContext().getUser().getUserId();

        CompanyPlatform companyPlatform = companyPlatformMapperExt.selectByCompanyId(userCompanyId);
        final boolean isAgent = Objects.nonNull(companyPlatform);//企业平台
        final boolean isOneLogin = isAgent && companyPlatform.getType() == PlatformApi.TYPE_ALONE;// 独立小程序

        // 是否授权标签
        final boolean hasArticle = Objects.nonNull(companyApiCrmMapper.selectCompanyContentOne(userCompanyId));

        // 优选平台
        Company company = companyBaseService.getById(userCompanyId);
        final boolean isSelectPlatform = 1 == company.getSelectState();

        // 菜单
        List<MenuTreeDto> menuTreeDtos = menuService.getAll(null, MenuService.TYPE_CRM_PC);
        List<Integer> menuOpen = menuService.getOpen(userId);
        List<UserInfoResponse.Menu> menus = ConvertUtils.listWithoutNull(menuTreeDtos, menuTreeDto -> {

            List<UserInfoResponse.Menu> childList = null;
            if (OneListUtil.isNotEmpty(menuTreeDto.getMenus())) {
                childList = Lists.newArrayListWithExpectedSize(menuTreeDto.getMenus().size());
                for (MenuTreeDto childDto : menuTreeDto.getMenus()) {
                    if (menuOpen.contains(childDto.getMenu().getMenuId())) {
                        if (!hasArticle && (81 == childDto.getMenu().getCode() || 82 == childDto.getMenu().getCode())) {//81 82: 获客海报 红木头条
                            continue;
                        }
                        if (isSelectPlatform && 32 == childDto.getMenu().getCode()) {//32:代理商品
                            continue;
                        } else if (!isSelectPlatform && 33 == childDto.getMenu().getCode()) {//33:代理商品
                            continue;
                        }
                        if (!isAgent && (83 == childDto.getMenu().getCode() || 84 == childDto.getMenu().getCode() || 85 == childDto.getMenu().getCode())) {// 分销
                            continue;
                        }
                        if (isOneLogin && 73 == childDto.getMenu().getCode()) {// 73: 合并员工列表
                            continue;
                        }
                        childList.add(UserInfoResponse.Menu.builder()
                                .code(childDto.getMenu().getCode())
                                .name(childDto.getMenu().getValue())
                                .page(childDto.getMenu().getPage())
                                .icon(childDto.getMenu().getIcon())
                                .build());
                    }
                }
            }
            if (OneListUtil.isEmpty(childList) && !menuOpen.contains(menuTreeDto.getMenu().getMenuId())) return null;

            return UserInfoResponse.Menu.builder()
                    .code(menuTreeDto.getMenu().getCode())
                    .name(menuTreeDto.getMenu().getValue())
                    .page(menuTreeDto.getMenu().getPage())
                    .icon(menuTreeDto.getMenu().getIcon())
                    .menus(childList)
                    .build();
        });

        UserInfoResponse response = UserInfoResponse.builder()
                .menus(menus)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "被合并列表")
    @PostMapping("/merge/list")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<UserMergeListResponse> mergeList(@RequestAttribute UserMergeListRequest request) {

        Company companyModel = companyBaseService.getById(request.getCId());
        String nameLike = SqlUtil.like(request.getName());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<User> users = userApiMapper.selectByCompanyId(companyModel.getCompanyKey(), nameLike);

        PageResponse2<UserMergeListResponse.User> mergeList = ConvertUtils.page2(users, user -> {
            return UserMergeListResponse.User.builder()
                    .userId(user.getUserId())
                    .name(user.getNickeName())
                    .phone(user.getPhone())
                    .avatar_url(user.getAvatarUrl())
                    .ctime(DateFormatUtils.ISO_8601_EXTENDED_DATETIME_FORMAT.format(user.getCreateTime()))
                    .build();
        });

        UserMergeListResponse response = new UserMergeListResponse();
        response.setUserList(mergeList);
        return ResultModel.success(response);
    }

    @ApiOperation(value = "合并到用户列表，默认前10名")
    @PostMapping("/merge/user")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel<UserMergeUserResponse> merge(@RequestAttribute UserMergeUserRequest request) {

        String nameLike = SqlUtil.like(request.getName());
        PageHelper.startPage(1, 10);
        List<User> users = userApiMapper.selectMergeUser(request.getCId(), nameLike);

        List<UserMergeUserResponse.User> mergeList = ConvertUtils.list(users, user -> {
            return UserMergeUserResponse.User.builder()
                    .id(user.getUserId())
                    .text(user.getNickeName())
                    .avatar_url(user.getAvatarUrl())
                    .build();
        });

        UserMergeUserResponse response = new UserMergeUserResponse();
        response.setList(mergeList);
        return ResultModel.success(response);
    }

    @ApiOperation(value = "合并到用户列表，默认前10名")
    @PostMapping("/merge")
    @SecurityAuthCheck(company = true, card = true)
    public ResultModel merge(@RequestAttribute UserMergeRequest request) {

        ResultModel resultModel = userFeign.merge(UserMergeDto.builder()
                .mergeUserId(request.getMergeUserId())
                .userId(request.getUserId())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }
}
